/**
 * 忘记密码页面组件
 * 
 * 功能说明：
 * - 提供忘记密码流程的完整实现
 * - 支持邮箱验证和密码重置
 * - 包含多个状态页面：请求重置、重置密码、成功页面
 * - 优雅的动画效果和交互反馈
 */

import React, { useState, useEffect } from 'react'
import { Form, Input, Button, Card, Typography, message } from 'antd'
import { MailOutlined, UserOutlined, LockOutlined, ArrowRightOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import authService from '@services/auth'

const { Title, Text } = Typography

/**
 * 忘记密码页面组件 - 直接验证身份并重置密码
 */
function ForgotPasswordPage() {
  const [form] = Form.useForm()
  const [isVisible, setIsVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()

  // 页面加载时添加渐入动画
  useEffect(() => {
    setIsVisible(true)
  }, [])

  /**
   * 处理密码重置提交
   * @param {Object} values - 表单数据
   */
  const handleResetPassword = async (values) => {
    try {
      setLoading(true)
      
      // 调用后端API直接重置密码
      const response = await authService.resetPasswordWithVerification({
        email: values.email,
        username: values.username,
        newPassword: values.newPassword,
        confirmPassword: values.confirmPassword
      })

      if (response.success) {
        message.success('密码重置成功，请使用新密码登录')
        setTimeout(() => {
          navigate('/login')
        }, 1500)
      }
    } catch (error) {
      console.error('重置密码失败:', error)
      message.error(error.message || '验证信息失败或重置密码失败，请检查输入')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div 
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '20px',
        background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
        position: 'relative',
        overflow: 'hidden'
      }}
    >
      {/* 背景装饰 */}
      <div style={{
        position: 'absolute',
        width: '400px',
        height: '400px',
        background: 'rgba(24, 144, 255, 0.05)',
        borderRadius: '50%',
        top: '-100px',
        right: '-100px',
        zIndex: 0
      }} />
      <div style={{
        position: 'absolute',
        width: '300px',
        height: '300px',
        background: 'rgba(24, 144, 255, 0.03)',
        borderRadius: '50%',
        bottom: '-150px',
        left: '-150px',
        zIndex: 0
      }} />
      
      <Card
        style={{
          width: '100%',
          maxWidth: 420,
          borderRadius: 16,
          boxShadow: '0 10px 40px rgba(0, 0, 0, 0.08)',
          border: 'none',
          background: 'white',
          position: 'relative',
          zIndex: 1,
          transition: 'opacity 0.5s ease, transform 0.5s ease',
          opacity: isVisible ? 1 : 0,
          transform: isVisible ? 'translateY(0)' : 'translateY(20px)'
        }}
      >
        {/* 头部标题 */}
        <div style={{ textAlign: 'center', marginBottom: 32, paddingTop: 16 }}>
          <div 
            style={{
              width: 80,
              height: 80,
              borderRadius: '50%',
              background: 'linear-gradient(135deg, #1890ff, #13c2c2)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              margin: '0 auto 20px',
              color: 'white',
              fontWeight: 'bold',
              fontSize: 32,
              boxShadow: '0 4px 20px rgba(24, 144, 255, 0.2)',
              transition: 'transform 0.3s ease'
            }}
          >
            校
          </div>
          <Title level={3} style={{ marginBottom: 8, fontSize: '24px', fontWeight: 600, color: '#333' }}>
            重置密码
          </Title>
          <Text type="secondary" style={{ fontSize: '16px', color: '#666' }}>
            二手交易平台
          </Text>
        </div>

        {/* 表单说明 */}
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Text type="secondary" style={{ fontSize: '16px', color: '#666', lineHeight: 1.5 }}>
            请输入您的邮箱、用户名和新密码来重置密码
          </Text>
        </div>

        {/* 重置密码表单 */}
        <Form
          form={form}
          name="reset-password-direct"
          layout="vertical"
          onFinish={handleResetPassword}
          autoComplete="off"
        >
          {/* 邮箱输入 */}
          <Form.Item
            name="email"
            rules={[
              {
                required: true,
                message: '请输入邮箱地址'
              },
              {
                type: 'email',
                message: '请输入有效的邮箱地址'
              }
            ]}
            style={{ marginBottom: 20 }}
          >
            <Input
              prefix={<MailOutlined style={{ color: '#1890ff' }} />}
              placeholder="注册邮箱"
              size="large"
              style={{ 
                borderRadius: 10,
                borderColor: '#e8e8e8',
                height: 48,
                fontSize: 16,
                transition: 'all 0.3s ease'
              }}
              className="custom-input"
            />
          </Form.Item>

          {/* 用户名输入 */}
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名'
              },
              {
                min: 3,
                message: '用户名至少3位'
              }
            ]}
            style={{ marginBottom: 20 }}
          >
            <Input
              prefix={<UserOutlined style={{ color: '#1890ff' }} />}
              placeholder="用户名"
              size="large"
              style={{ 
                borderRadius: 10,
                borderColor: '#e8e8e8',
                height: 48,
                fontSize: 16,
                transition: 'all 0.3s ease'
              }}
              className="custom-input"
            />
          </Form.Item>

          {/* 新密码输入 */}
          <Form.Item
            name="newPassword"
            rules={[
              {
                required: true,
                message: '请输入新密码'
              },
              {
                min: 6,
                message: '密码长度至少6位'
              },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
                message: '密码必须包含字母和数字'
              }
            ]}
            style={{ marginBottom: 20 }}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: '#1890ff' }} />}
              placeholder="新密码（至少6位，含字母和数字）"
              size="large"
              style={{ 
                borderRadius: 10,
                borderColor: '#e8e8e8',
                height: 48,
                fontSize: 16,
                transition: 'all 0.3s ease'
              }}
              className="custom-input"
            />
          </Form.Item>

          {/* 确认新密码输入 */}
          <Form.Item
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              {
                required: true,
                message: '请确认新密码'
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                }
              })
            ]}
            style={{ marginBottom: 28 }}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: '#1890ff' }} />}
              placeholder="确认新密码"
              size="large"
              style={{ 
                borderRadius: 10,
                borderColor: '#e8e8e8',
                height: 48,
                fontSize: 16,
                transition: 'all 0.3s ease'
              }}
              className="custom-input"
            />
          </Form.Item>

          {/* 提交按钮 */}
          <Form.Item style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
              icon={!loading && <ArrowRightOutlined />}
              style={{
                width: '100%',
                borderRadius: 10,
                height: 48,
                fontSize: 16,
                backgroundColor: '#1890ff',
                fontWeight: 500,
                transition: 'all 0.3s ease',
                boxShadow: '0 4px 12px rgba(24, 144, 255, 0.2)'
              }}
              className="reset-button"
              onMouseEnter={(e) => {
                if (!loading) {
                  e.currentTarget.style.backgroundColor = '#40a9ff'
                  e.currentTarget.style.transform = 'translateY(-1px)'
                  e.currentTarget.style.boxShadow = '0 6px 16px rgba(24, 144, 255, 0.3)'
                }
              }}
              onMouseLeave={(e) => {
                if (!loading) {
                  e.currentTarget.style.backgroundColor = '#1890ff'
                  e.currentTarget.style.transform = 'translateY(0)'
                  e.currentTarget.style.boxShadow = '0 4px 12px rgba(24, 144, 255, 0.2)'
                }
              }}
            >
              {loading ? '重置中...' : '确认重置密码'}
            </Button>
          </Form.Item>

          {/* 返回登录链接 */}
          <div style={{ textAlign: 'center' }}>
            <Button 
              type="link" 
              onClick={() => navigate('/login')}
              style={{ color: '#1890ff', fontSize: 14 }}
            >
              返回登录
            </Button>
          </div>
        </Form>
      </Card>
      
      {/* 添加全局样式 */}
      <style>{`
        /* 自定义输入框焦点样式 */
        .custom-input:focus {
          border-color: #1890ff !important;
          box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
        }
        
        /* 自定义输入框过渡效果 */
        .custom-input:hover {
          border-color: #1890ff !important;
        }
      `}</style>
    </div>
  )
}

export default ForgotPasswordPage